<?php
require_once(Kohana::find_file('vendor','phprpc/phprpc_client'));

/**
 * Created by PhpStorm.
 * User: locove
 * Date: 15-4-2
 * Time: 上午9:14
 * 采购支持模块重置
 */
class Controller_Sirens extends Controller_Admin
{
    public function action_index()
    {
        $this->title = '采购支持预警（新）';
        $opera       = User::active_user()->nick;

        $sql     = "SELECT UNIX_TIMESTAMP(`add_time`) `add_time` FROM `sirens` LIMIT 1";
        $minTime = DB::query(Database::SELECT,$sql)->execute('newerp')->get('add_time',0);
        $sql     = "SELECT old FROM `sirens` LIMIT 1";
        $oldOrNot = DB::query(Database::SELECT,$sql)->execute('newerp')->get('old',0);

        $bo1 = isset($_GET['old']) && $_GET['old'] == 'on' && !$oldOrNot;
        $bo2 = !isset($_GET['old']) && $oldOrNot;

        if($bo1 || $bo2) {
            DB::query(Database::DELETE,"TRUNCATE TABLE `sirens`")
                ->execute('newerp');
            DB::query(Database::DELETE,"TRUNCATE TABLE `sirens_best`")
                ->execute('newerp');
            $this->doSirens();
        }else{
            if($_SERVER['REQUEST_TIME']-$minTime>300){
                DB::query(Database::DELETE,"TRUNCATE TABLE `sirens`")
                    ->execute('newerp');
                DB::query(Database::DELETE,"TRUNCATE TABLE `sirens_best`")
                    ->execute('newerp');
                $this->doSirens();
            }
        }

        $sri = "FROM `sirens` JOIN sirens_best ON sirens.sku = sirens_best.sku WHERE 1 ";
        if(isset($_GET['sku']) && $_GET['sku']){
            $sri .= "AND sirens.`sku`='".$_GET['sku']."' ";
        }

        $now_sec = time();
        $tom_sec = strtotime(date("Y-m-d 08:30:00", strtotime("+1 day")));
        $tom_sec_3 = strtotime(date("Y-m-d 08:30:00", strtotime("+3 day")));
        $tom_sec_7 = strtotime(date("Y-m-d 08:30:00", strtotime("+7 day")));

        //采购预警和支持分开
        if(isset($_GET['past']) && $_GET['past']) {
            $sri .= " AND {$now_sec} + `sirens_best`.`do_sec` <= 0 ";
        }elseif(isset($_GET['day']) && $_GET['day']){
            switch(trim($_GET['day'])){
                case 1:
                    $sri .= "AND {$now_sec} + `sirens_best`.`do_sec` > 0 AND {$now_sec} + `sirens_best`.`do_sec` <= {$tom_sec} ";
                    break;
                case 3:
                    $sri .= "AND {$now_sec} + `sirens_best`.`do_sec` > {$tom_sec} AND {$now_sec} + sirens_best.`do_sec` <= {$tom_sec_3} ";
                    break;
                case 7:
                    $sri .= "AND {$now_sec} + `sirens_best`.`do_sec` > {$tom_sec_3} AND {$now_sec} + sirens_best.`do_sec` <= {$tom_sec_7} ";
                    break;
                default:
                    $sri .= "AND {$now_sec} + `sirens_best`.`do_sec` <= {$tom_sec} ";
                    break;
            }
        }

        $f = FALSE;
        if(isset($_GET['username'])){
            if($_GET['username']){
                $_skus = Skusystemapi::getUserAllSkuByNick($_GET['username']);
            }else{
                $f = TRUE;
            }
        }else{
            $_skus = Skusystemapi::getUserAllSkuByNick(User::active_user()->nick);
        }

        if(!$f){
            if($_skus){
                $skus_str = '';
                foreach($_skus as $_s){
                    $skus_str .= $skus_str?",'".$_s['sku']."'":"'".$_s['sku']."'";
                }
                $sri .= " AND `sirens`.`sku` IN ({$skus_str}) ";
            }else{
                $sri .= " AND `sirens`.`id`=0 ";
            }
        }

        isset($_GET['download']) || $lc = DB::query(Database::SELECT,"SELECT COUNT(`sku`) AS `num` FROM (SELECT `sirens`.`sku` {$sri} GROUP BY `sirens`.`sku`) a")->execute('newerp')->get('num',0);

        isset($_GET['download']) || $page = Pagination::factory(array(
            'items_per_page' => 10,
            'total_items'    => $lc,
            'uri'            => $this->request->uri(),
        ));

        $sri = "SELECT `sirens`.`sku`, `sirens`.`actual`, `sirens`.`hold`, `sirens`.`onway`, `sirens`.`safe`,`sirens`.`sup_sec`,
        IF((`sirens`.`sup_sec`<0),CONCAT('-',FLOOR(ABS(`sirens`.`sup_sec`) / 86400), FROM_UNIXTIME(ABS(`sirens`.`sup_sec`)+61200, '天 %H:%i:%s')),CONCAT(FLOOR(`sirens`.`sup_sec` / 86400), FROM_UNIXTIME(`sirens`.`sup_sec`+61200, '天 %H:%i:%s'))) `sup_sec_name`,
             `sirens`.`add_time` {$sri} GROUP BY `sirens`.`sku` ";

        isset($_GET['download']) || $sri = "{$sri} LIMIT {$page->items_per_page} OFFSET {$page->_offset}";

        $lists = DB::query(Database::SELECT,$sri)
            ->execute('newerp')
            ->as_array('sku');

        isset($_GET['download']) && $this->buildCsv($lists);
        $sku_sus = $lp = $ps = $su_ns = $sku_ns = $cost = array();
        if(!empty($lists)){
            $skus = array_keys($lists);

            $sus = DB::select('sku','su_id','do_sec','ldt_sec',
                DB::expr("CONCAT(FLOOR(`ldt_sec` / 86400), FROM_UNIXTIME(`ldt_sec`+61200, '天 %H:%i:%s')) ldt_sec_name"),
                DB::expr("ROUND(`def_sec` / 86400,3) def_sec_name"))
                ->from('sirens_best')
                ->where('sku','in',$skus)
                ->execute('newerp')
                ->as_array();

            $su_ids = array();
            foreach($sus as $su){
                $sku_sus[$su['sku']][$su['su_id']]['ldt_sec'] = $su['ldt_sec'];
                $sku_sus[$su['sku']][$su['su_id']]['ldt_sec_name'] = $su['ldt_sec_name'];
                $sku_sus[$su['sku']][$su['su_id']]['def_sec_name'] = $su['def_sec_name'];
                $sku_sus[$su['sku']][$su['su_id']]['do_sec']  = $su['do_sec'];
                $sku_sus[$su['sku']][$su['su_id']]['best']    = date("Y-m-d H:i:s",time()+$su['do_sec']);
                $su_ids[]                                     = $su['su_id'];
            }

            $skus_status = skusystemapi::getSkuAndStatus($skus);
            $sts = array();
            foreach($skus_status as $st) {
                $sts[$st['sku']] = $st['status'];
            }



            $lps = DB::select('purchaseorder_details.purchaseorder_id','purchaseorder_details.purchaseorder_id','purchaseorder_details.supplier','purchaseorder_details.sku','purchaseorder_details.quantity','purchaseorder_details.details_date')
                ->from('purchaseorder_details')
                ->join('purchaseorders')
                ->on('purchaseorders.id','=','purchaseorder_details.purchaseorder_id')
                ->where('purchaseorder_details.sku','in',$skus)
                ->where('purchaseorder_details.supplier','in', $su_ids)
                ->where('purchaseorders.status','!=',100)
                ->where('purchaseorder_details.status','!=', 100)
                ->order_by('purchaseorders.id', 'DESC')
                ->execute('newerp')
                ->as_array();

            $lp = array();
            foreach($lps as $pd){
                if(isset($lp[$pd['sku']][$pd['supplier']]))
                {
                    continue;
                }
                $lp[$pd['sku']][$pd['supplier']] = $pd['details_date'];
            }


            $skus   = "'".join("','",$skus)."'";
            $su_ids = "'".join("','",$su_ids)."'";

//            $sri = "SELECT `sku`,`supplier`,`details_date` FROM (
//                SELECT
//                    `purchaseorder_details`.`id`,`purchaseorder_details`.`sku`,`purchaseorder_details`.`supplier`,`purchaseorder_details`.`details_date`
//                FROM
//                    `purchaseorder_details`
//                JOIN `purchaseorders`
//                ON `purchaseorders`.`id`=`purchaseorder_details`.`purchaseorder_id`
//                WHERE
//                    `purchaseorder_details`.`sku`
//                IN ({$skus})
//                AND `purchaseorder_details`.`supplier` IN ({$su_ids})
//                AND `purchaseorders`.`status`!=100
//                AND `purchaseorder_details`.`status`!=100
//                ORDER BY `purchaseorder_details`.`id` DESC) a
//                GROUP BY `sku`,`supplier`";
//
//            $lps = DB::query(Database::SELECT,$sri)
//                ->execute('newerp')
//                ->as_array();
//            $lp  = array();
//            foreach($lps as $l){
//                $lp[$l['sku']][$l['supplier']] = $l['details_date'];
//            }

            $client = new PHPRPC_Client();
            $client->useService("http://192.168.5.5:802/profitapi/execute");

            //成本价
            $sri = "select `sku`,`num` from `skusystem_price` where `sku` in ({$skus})";
            $cos = json_decode($client->getinfo($sri),TRUE);
            $cos = DB::query(Database::SELECT,$sql)->execute('skusystemread')->as_array();

            foreach($cos as $p){
                $cost[$p['sku']] = $p['num'];
            }

            //每个供应商的采购价格
            $sri = "select `sku`,`supplier_id`,`price`
            from `skusystem_supplier_skus`
            where `sku` in ({$skus})
            and `supplier_id` in ({$su_ids})";
            //$prs = json_decode($client->getinfo($sri),TRUE);
            $prs = DB::query(Database::SELECT,$sri)->execute('newerp')->as_array();
            foreach($prs as $p){
                $ps[$p['sku']][$p['supplier_id']] = $p['price'];
            }

            //供应商名字
            $sri      = "SELECT `id`,`name` FROM `skusystem_suppliers` WHERE `id` IN ({$su_ids})";
            //$su_names = json_decode($client->getinfo($sri),TRUE);
            $su_names = DB::query(Database::SELECT,$sri)->execute('newerp')->as_array();
            foreach($su_names as $n){
                $su_ns[$n['id']] = $n['name'];
            }

            //获取sku的中文名称
            $sri = "SELECT a.`sku`,b.`name`
            FROM `skusystem_cnname` as b
            JOIN `skusystem_sku_cnname` as a
            ON a.`attr_id`=b.`id`
            WHERE a.`sku` IN ({$skus})";

            //$sku_names = json_decode($client->getinfo($sri),TRUE);
            $sku_names = DB::query(Database::SELECT,$sri)->execute('newerp')->as_array();
            foreach($sku_names as $s){
                $sku_ns[$s['sku']] = $s['name'];
            }

            if(isset($_GET['old'])&&$_GET['old']) {
                $daysales = sirens::getOldDaySale($skus);
            }else{
                $sql = "SELECT `sku`,SUM(`daysale`) `daysale`
                FROM `sku_sales`
                WHERE `count_date`='".date('Y-m-d',$_SERVER['REQUEST_TIME']-86400)."'
                AND `sku` IN({$skus})
                GROUP BY `sku`";

                $daysales = DB::query(Database::SELECT,$sql)
                    ->execute('newerp')
                    ->as_array('sku','daysale');
            }
        }

        $last_time = DB::select('add_time')
            ->from('sirens')
            ->limit(1)
            ->execute('newerp')
            ->get('add_time','');

        $view = View::factory('sirens');
        $view->set('get',$_GET);
        $view->set('first',$page->current_first_item);
        $view->set('opera',$opera);
        $view->set('page',$page);
        $view->set('lists',$lists);
        $view->set('sku_sus',$sku_sus);
        $view->set('lp',$lp);
        $view->set('ps',$ps);
        $view->set('cost',$cost);
        $view->set('su_ns',$su_ns);
        $view->set('sku_ns',$sku_ns);
        $view->set('daysales',isset($daysales) ? $daysales : '');
        $view->set('lc',$lc);
        $view->set('sts',isset($sts) ? $sts  : '');
        $view->set('last_time',$last_time);
        $this->response->body($view);
    }

    /**
     * 单个SKU系统下单跳转到新的页面了
     */
    public function action_purchase()
    {
        $this->title = '单个SKU系统下单';

        if(isset($_GET['sku']) and trim($_GET['sku'])){
            $sql = "SELECT `sirens`.`sku`, `sirens`.`actual`, `sirens`.`hold`, `sirens`.`onway`, `sirens`.`safe`,`sirens`.`sup_sec`,
                IF((`sirens`.`sup_sec`<0),CONCAT('-',FLOOR(ABS(`sirens`.`sup_sec`) / 86400), FROM_UNIXTIME(ABS(`sirens`.`sup_sec`)+61200, '天 %H:%i:%s')),CONCAT(FLOOR(`sirens`.`sup_sec` / 86400), FROM_UNIXTIME(`sirens`.`sup_sec`+61200, '天 %H:%i:%s'))) `sup_sec_name`,
                `sirens`.`add_time` FROM `sirens` WHERE `sirens`.`sku`='{$_GET['sku']}'";

            $lists = DB::query(Database::SELECT,$sql)
                ->execute('newerp')
                ->current();

            if(!empty($lists)){
                $sirens_best = DB::select('sku','su_id','do_sec','ldt_sec',DB::expr("CONCAT(FLOOR(`ldt_sec` / 86400), FROM_UNIXTIME(`ldt_sec`+61200, '天 %H:%i:%s')) ldt_sec_name"))
                    ->from('sirens_best')
                    ->where('sku','=',$_GET['sku'])
                    ->where('su_id','=',$_GET['su_id'])
                    ->execute('newerp')
                    ->current();

                $lists['ldt_sec']     = $sirens_best['ldt_sec'];
                $lists['do_sec_name'] = date("Y-m-d H:i:s",time()+$sirens_best['do_sec']);

                /*$client = new PHPRPC_Client();
                $client->useService("http://192.168.5.5:802/profitapi/execute");*/

                //获取sku的中文名称
                $sql = "SELECT a.`sku`,b.`name`
                    FROM `skusystem_cnname` as b
                    JOIN `skusystem_sku_cnname` as a
                    ON a.`attr_id`=b.`id`
                    WHERE a.`sku` = '{$_GET['sku']}'";

                //$sku_names         = json_decode($client->getinfo($sql),TRUE);
                $sku_names = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array();
                $lists['sku_name'] = $sku_names[0]['name'];

                if(isset($_GET['old'])) {
                    $daysales = sirens::getOldDaySale("'".$_GET['sku']."'");
                    $lists['daysale'] = isset($daysales[$_GET['sku']])?$daysales[$_GET['sku']]:0;
                }else{
                    $sql = "SELECT `sku`,SUM(`daysale`) `daysale`
                    FROM `sku_sales`
                    WHERE `count_date`='".date('Y-m-d',$_SERVER['REQUEST_TIME']-86400)."'
                    AND `sku` = '{$_GET['sku']}'";

                    $lists['daysale'] = DB::query(Database::SELECT,$sql)
                        ->execute('newerp')
                        ->get('daysale',0);
                }
            }
            /**
             * 联系人信息
             */
            $contacts = Newerpclientapi::getSupplierContacts(trim($_GET['su_id']));
            $view = View::factory('sirens_sku');
            $view->set('types', Kohana::$config->load('ratetypes')->get('types'));
            $view->set('supplier_for_sku',newerpclientapi::getSupplierById($_GET['su_id']));
            $view->set('supplier_payways',Supplierbank::do_select(array('supplier_id' => $_GET['su_id'],'active_status'=>1)));
            $view->set('tax_ways',Service_warning::get_tax_ways());
            $view->set('skulists',$lists);
            $view->set('supplier_id',$_GET['su_id']);
            $view->set('contacts_info',$contacts);

            $this->response->body($view);
        }
    }

    /**
     * 供应商下单跳转新的页面
     */
    public function action_purchase_supplier()
    {
        $this->title = '供应商下单';
        if(isset($_GET['supplier']) && isset($_GET['su_id'])){
            $purchaseorder_id = Service_purchaseadd::get_purchaseorder_num();
            $view = View::factory('sirens_supplier');

            /**
             * 联系人信息
             */
            $contacts = Newerpclientapi::getSupplierContacts(trim($_GET['su_id']));
            if($contacts)
            {
                $view->set('contacts_info',$contacts);
            }

            /**
             * 付款方式
             */
            $payways = Supplierbank::get_supplier_payways_by_supplier_id(trim($_GET['su_id'])); //var_dump($payways);
            if($payways)
            {
                $view->set('pay_ways', $payways);
            }

            /**
             * 付款帐号
             */
            $bankinfos = Supplierbank::get_supplier_bankinfo_by_supplier_id_new(trim($_GET['su_id']));
            if($bankinfos)
            {
                $view->set('payaccountinfos',$bankinfos);
            }

            $coins = DB::select('number', 'value')->from('statusdics')
                ->where('table', '=', 'purchaseorders')
                ->where('colum_name', '=', 'coin')
                ->execute('newerp')
                ->as_array('number', 'value');
            $view->set('coins', $coins);

            $view->set('purchaseorder_id',++$purchaseorder_id)
                ->set('supplier',$_GET['supplier'])
                ->set('su_id',$_GET['su_id']);
            $this->response->body($view);
        }
    }

    //预警首页
    public function doSirens()
    {
        $sirens = new Sirens();

        $sql = "SELECT upper(`sku`) `sku` FROM `ldt_ord` WHERE `status` NOT IN(2,4,5,6,9) GROUP BY `sku`";
        $sirens->skus = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array(NULL,'sku');
        $sirens->old = isset($_GET['old'])?TRUE:FALSE;

        $sirens->doSirens();
    }

    public function buildCsv($lists) {
        set_time_limit(0);
        $_GET['date'] = $_SERVER['REQUEST_TIME'];
        $md5 = md5(join('::',$_GET));

        $file = dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/disk/".$md5.".csv";

        if(!is_file($file)) {
            $fp =fopen($file, 'a+');
            flock($fp, LOCK_EX);
            ftruncate($fp, 0);

            fwrite($fp,iconv('UTF-8','GB18030//IGNORE','SKU,中文名称,供应商,实际库存数量,总在途数量,总未发数量,总可用数量,日均销量,可支持天数,预交期,成本价,最近采购时间,最佳下单日期,建议采购量,销售状态')."\r\n");

            $sku_sus = $lp = $ps = $su_ns = $sku_ns = array();
            if(!empty($lists)){
                $skus = array_keys($lists);

                $sus = DB::select('sku','su_id','do_sec','ldt_sec',DB::expr("CONCAT(FLOOR(`ldt_sec` / 86400), FROM_UNIXTIME(`ldt_sec`+61200, '天 %H:%i:%s')) ldt_sec_name"))
                    ->from('sirens_best')
                    ->where('sku','in',$skus)
                    ->order_by(array('sku', 'ldt_sec'))
                    ->execute('newerp')
                    ->as_array();

                $su_ids = array();
                $su_ldts = array();
                foreach($sus as $su){
                    $su_ldts[$su['sku']][] = $su['ldt_sec'];
                    $sku_sus[$su['sku']][$su['su_id']]['ldt_sec'] = $su['ldt_sec'];
                    $sku_sus[$su['sku']][$su['su_id']]['ldt_sec_name'] = $su['ldt_sec_name'];
                    $sku_sus[$su['sku']][$su['su_id']]['def_sec_name'] = $su['def_sec_name'];
                    $sku_sus[$su['sku']][$su['su_id']]['do_sec']  = $su['do_sec'];
                    $sku_sus[$su['sku']][$su['su_id']]['best']    = date("Y-m-d H:i:s",time()+$su['do_sec']);
                    $su_ids[]                                     = $su['su_id'];
                }

                foreach($su_ldts as &$su_ldt) {
                    rsort($su_ldt);
                }

                $skus_status = skusystemapi::getSkuAndStatus($skus);
                $sts = array();
                foreach($skus_status as $st) {
                    $sts[$st['sku']] = $st['status'];
                }


//                $lps = DB::select('purchaseorder_details.purchaseorder_id','purchaseorder_details.purchaseorder_id','purchaseorder_details.supplier','purchaseorder_details.sku','purchaseorder_details.quantity','purchaseorder_details.details_date')
//                    ->from('purchaseorder_details')
//                    ->join('purchaseorders')
//                    ->on('purchaseorders.id','=','purchaseorder_details.purchaseorder_id')
//                    ->where('purchaseorder_details.sku','in',$skus)
//                    ->where('purchaseorder_details.supplier','in', $su_ids)
//                    ->where('purchaseorders.status','!=',100)
//                    ->where('purchaseorder_details.status','!=', 100)
//                    ->order_by('purchaseorders.id', 'DESC')
//                    ->execute('newerp')
//                    ->as_array();
//
//                $lp = array();
//                foreach($lps as $pd){
//                    if(isset($lp[$pd['sku']][$pd['supplier']]))
//                    {
//                        continue;
//                    }
//                    $lp[$pd['sku']][$pd['supplier']] = $pd['details_date'];
//                }

                $lps = DB::select('purchaseorder_details.purchaseorder_id','purchaseorder_details.purchaseorder_id','purchaseorder_details.supplier','purchaseorder_details.sku','purchaseorder_details.quantity','purchaseorder_details.details_date')
                    ->from('purchaseorder_details')
                    ->join('purchaseorders')
                    ->on('purchaseorders.id','=','purchaseorder_details.purchaseorder_id')
                    ->where('purchaseorder_details.sku','in',$skus)
                    ->where('purchaseorders.status','!=',100)
                    ->where('purchaseorder_details.status','!=', 100)
                    ->order_by('purchaseorders.id', 'DESC')
                    ->execute('newerp')
                    ->as_array();

                $lp = array();
                foreach($lps as $pd){
                    if(isset($lp[$pd['sku']]))
                    {
                        continue;
                    }
                    $lp[$pd['sku']][$pd['supplier']] = $pd['details_date'];
                }



                $skus   = "'".join("','",$skus)."'";
                $su_ids = "'".join("','",$su_ids)."'";

//                $sri = "SELECT MAX(`id`),`sku`,`supplier`,`details_date` FROM (
//                SELECT
//                    `purchaseorder_details`.`id`,`purchaseorder_details`.`sku`,`purchaseorder_details`.`supplier`,`purchaseorder_details`.`details_date`
//                FROM
//                    `purchaseorder_details`
//                JOIN `purchaseorders`
//                ON `purchaseorders`.`id`=`purchaseorder_details`.`purchaseorder_id`
//                WHERE
//                    `purchaseorder_details`.`sku`
//                IN ({$skus})
//                AND `purchaseorder_details`.`supplier` IN ({$su_ids})
//                AND `purchaseorders`.`status`!=100
//                AND `purchaseorder_details`.`status`!=100
//                ORDER BY `purchaseorder_details`.`id` DESC) a
//                GROUP BY `sku`,`supplier`";
//
//                $lps = DB::query(Database::SELECT,$sri)
//                    ->execute('newerp')
//                    ->as_array();
//                $lp  = array();
//                foreach($lps as $l){
//                    $lp[$l['sku']][$l['supplier']] = $l['details_date'];
//                }

                /*$client = new PHPRPC_Client();
                $client->useService("http://192.168.5.5:802/profitapi/execute");*/

                //成本价
                $sri = "select `sku`,`num` from `skusystem_price` where `sku` in ({$skus})";
                //$prs = json_decode($client->getinfo($sri),TRUE);
                $prs = DB::query(Database::SELECT,$sri)->execute('newerp')->as_array();
                foreach($prs as $p){
                    $ps[$p['sku']] = $p['num'];
                }

                //供应商名字
                $sri      = "SELECT `id`,`name` FROM `skusystem_suppliers` WHERE `id` IN ({$su_ids})";
                //$su_names = json_decode($client->getinfo($sri),TRUE);
                $su_names = DB::query(Database::SELECT,$sri)->execute('newerp')->as_array();
                foreach($su_names as $n){
                    $su_ns[$n['id']] = $n['name'];
                }

                //获取sku的中文名称
                $sri = "SELECT a.`sku`,b.`name`
                    FROM `skusystem_cnname` as b
                    JOIN `skusystem_sku_cnname` as a
                    ON a.`attr_id`=b.`id`
                    WHERE b.`sku` IN ({$skus})";

                //$sku_names = json_decode($client->getinfo($sri),TRUE);
                $sku_names = DB::query(Database::SELECT,$sri)->execute('newerp')->as_array();
                foreach($sku_names as $s){
                    $sku_ns[$s['sku']] = $s['name'];
                }

                if(isset($_GET['old'])) {
                    $daysales = sirens::getOldDaySale($skus);
                } else {
                    $sql = "SELECT `sku`,SUM(`daysale`) `daysale`
                    FROM `sku_sales`
                    WHERE `count_date`='".date('Y-m-d',$_SERVER['REQUEST_TIME']-86400)."'
                    AND `sku` IN({$skus})
                    GROUP BY `sku`";

                    $daysales = DB::query(Database::SELECT,$sql)
                        ->execute('newerp')
                        ->as_array('sku','daysale');
                }

                foreach($lists as $list) {
                    $sku_name = iconv('UTF-8','GB18030//IGNORE',isset($sku_ns[$list['sku']])?$sku_ns[$list['sku']]:'');
                    $can = $list['actual'] + $list['onway'] - $list['hold'];
                    $price = isset($ps[$list['sku']])?$ps[$list['sku']]:0;
                    $sup_sec_name = iconv('UTF-8','GB18030//IGNORE',$list['sup_sec_name']);
                    $ds = isset($daysales[$list['sku']])?$daysales[$list['sku']]:0;
                    $st_n = iconv('UTF-8','GB18030//IGNORE',isset($sts[$list['sku']])?$sts[$list['sku']]:'');
                    foreach($sku_sus[$list['sku']] as $su_id=>$p) {
                        if(!isset($lp[$list['sku']][$su_id]))continue;
                        if($p['ldt_sec'] != $su_ldts[$list['sku']][0])continue;

                        $su_name = iconv('UTF-8','GB18030//IGNORE',isset($su_ns[$su_id])?$su_ns[$su_id]:'');


                        $ldt_sec_name = iconv('UTF-8','GB18030//IGNORE',$p['ldt_sec_name']);

                        $_lp = isset($lp[$list['sku']][$su_id])?$lp[$list['sku']][$su_id]:'';

                        $best = date("Y-m-d H:i:s",time()+$p['do_sec']);

                        $do = 0;
                        if($ds){
                            $do=ceil($daysales[$list['sku']]*(($p['ldt_sec']-$list['sup_sec'])/(60*60*24)+14));
                            $do>0 && $do = ceil($do);
                        }
                        $sku = trim(str_replace(" ", "", $list['sku']));
                        $temp = "{$sku},\"{$sku_name}\"\t,\"{$su_name}\"\t,{$list['actual']},{$list['onway']},{$list['hold']},\"{$can}\"\t,{$ds},\"{$sup_sec_name}\"\t,\"{$ldt_sec_name}\"\t,\"{$price}\"\t,\"{$_lp}\"\t,\"{$best}\"\t,{$do},\"{$st_n}\"\t\r\n";
                        fwrite($fp,$temp);
                    }
                }
            }
            fclose($fp);
        }
        echo $md5;
        exit;
    }

    public function action_download() {
        set_time_limit(0);
        header('Content-Type: application/download'); //下载头
        header('Content-Transfer-Encoding: binary'); //二进制
        header('Content-Disposition: attachment; filename='.iconv('UTF-8','GB18030//IGNORE','采购预警管理').'.csv'); //文件名
        header('Pragma:no-cache'); //不缓存

        $path = dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/disk/'.$_GET['md5'].'.csv';
        $fp   = fopen($path,'r');
        flock($fp,LOCK_SH); //加共享锁
        while(!feof($fp)){ //读取数据
            echo fread($fp,8192);
        }
        fclose($fp);

        exit;
    }

    //临时加的一个状态修改功能
    public function action_update_ldt_ord()
    {
        $skus = DB::select('sku')->from('ldt_ord')->group_by('sku')->execute('newerp')->as_array(NULL,'sku');
        $skus_status = skusystemapi::getSkuAndStatus($skus);
        $sts = array();
        foreach($skus_status as $st) {
            $sts[$st['sku']] = $st['status_id'];
        }
        foreach($skus as $sku)
        {
            $s = isset($sts[$sku])?$sts[$sku]:1;
            if($s==1)continue;
            DB::update('ldt_ord')->set(array('status'=>$s))->where('sku','=',$sku)->execute('newerp');
        }
    }

    //人工定义一个交期
    public function action_update_ldt()
    {
        $re = array('ok'=>0);
        $ldt_sec = $_POST['def_sec'] * 86400;

        $re['ok'] = DB::update('ldt_ord')
            ->set(array('def_sec'=>$ldt_sec))
            ->where('sku','=',$_POST['sku'])
            ->and_where('su_id','=',$_POST['su_id'])
            ->execute('newerp');

        $have = DB::select('id','sup_sec')->from('sirens')
            ->where('sku','=',$_POST['sku'])
            ->execute('newerp')
            ->current();

        if(!empty($have)) {
            $re['ok'] = -1;
            $do_sec = $have['sup_sec'] - $ldt_sec;
            $re['best'] = date("Y-m-d H:i:s",time() + $do_sec);

            DB::update('sirens_best')->set(array('def_sec'=>$ldt_sec,'do_sec'=>$do_sec))
                ->where('sku','=',$_POST['sku'])
                ->and_where('su_id','=',$_POST['su_id'])
                ->execute('newerp');

            $re['num'] = ceil($_POST['day_sale']*(-$do_sec/(60*60*24)+14));

        }
        echo json_encode($re);
        exit;
    }

    //对于活动SKU的剔除
    public function action_active() {
        for($i=1; $i<5; $i++) {
            checkstock::activeOut($i);
        }
    }
}